import {messages, uniqueObjArr, formatNumber} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Form, Input, Popconfirm, Select, Popover, Switch, Button, message, InputNumber, notification } from 'antd';
import 'styles/components/template/add-table-cell.scss'
import ResizeTable from './resize-table'
import Chooser from 'components/chooser';
import config from "config";
import FileUpload from 'components/file-upload'
import SlideFrame from 'components/slide-frame';
import httpFetch from 'share/httpFetch'

const { Option } = Select

class EditableCell extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: this.props.value,
      originValue: this.props.value,
      column: this.props.column,
      formTypeData: [],
      record: this.props.record,
      user: this.props.user,
      selectedRowKeys: [],
      selectedOID: []
    }
  }

  componentWillReceiveProps (nextProps) {
    let {  value } = nextProps
    if(value != this.state.value){
      this.setState({value})
    }
  }

  showDraw(value){
    this.props.clickFun(value)
  }

  // 礼品类型的联动
  onChange = (value, record) => {
    let { column, user } = this.props
    if (column.dataIndex === 'type') {
      let applyQuantity = Number(this.props.form.getFieldValue('applyQuantity'))
      let unitPrice = Number(value.split(',')[1])
      this.props.form.setFieldsValue({
        unitPrice,
        amount: applyQuantity ? applyQuantity * unitPrice : ''
      })
    }else if (column.dataIndex === 'sendWayText') {
      let data = value.split(',')
      if (data[0] === '自取') {
        this.props.isRequiredFun(false, 'deliveryInfo')
        this.props.form.setFieldsValue({
          link: user.fullName,
          phone: user.mobile
        })
      } else {
        this.props.isRequiredFun(true, 'deliveryInfo')
        this.props.form.setFieldsValue({
          link: '',
          phone: ''
        })
      }
    }else if(column.dataIndex === 'address'){
      let remark = value.split(',')[1];
      const [province, city, districtsAndCounties, detailedAddress, postalCode] = remark.split('-');

      this.props.form.setFieldsValue({
        province,
        city,
        districtsAndCounties,
        detailedAddress,
        postalCode
      })
    }else if(column.dataIndex === 'gift' && this.props.operationKey == 'receiver'){
      let type = value.split(',')[2];
      this.props.form.setFieldsValue({
        giftType:''
      })
      this.props.onGiftChange(type)
    }
    else if(column.dataIndex === 'giftType' && this.props.operationKey == 'receiver'){
      let applyQuantity = Number(this.props.form.getFieldValue('quantity'))
      let unitPrice = Number(value.split(',')[1])
      this.props.form.setFieldsValue({
        unitPrice,
        amount: applyQuantity ? applyQuantity * unitPrice : ''
      })
    }
  }

  // 接收人信息12个月内是否超过2次
  switchChange = (value) => {
    this.props.isRequiredFun(value, 'remark')
  }

  // 申请数量的联动
  onInput = (value) => {
    let { column, record } = this.props
    if (column.dataIndex === 'applyQuantity') {
      let receiveQuantity = Number(value)
      let unitPrice = Number(this.props.form.getFieldValue('unitPrice'))
      this.props.form.setFieldsValue({
        receiveQuantity,
        amount: receiveQuantity && unitPrice ? receiveQuantity * unitPrice : ''
      })
    } else if (column.dataIndex === 'receiveQuantity') {
      let unitPrice = Number(record.unitPrice)
      let amount = value * unitPrice
      this.props.form.setFieldsValue({
        amount
      })
    }
    else if (column.dataIndex === 'quantity') {
      if(this.props.form.getFieldValue('giftType')){
        let quantity = Number(value)
        let unitPrice = this.getUnitPrice() || record.unitPrice
        this.props.form.setFieldsValue({
          amount: quantity && unitPrice ? quantity * unitPrice : ''
        })
      }
    }
  }

  getUnitPrice(){
    window.tt = this
    let giftType = this.props.form.getFieldValue('giftType')
    // Number((this.props.form.getFieldValue('giftType')||'').split(',')[1])
    let unitPrice = undefined
    try {
      if(!/,\d+/.test(giftType)) {
        giftType = this.props.form.getFieldInstance('giftType').props.children.map(i=> i.props).find(i=> i.children === giftType).value
        // 这里表示回显的情况下直接修改数据
      }

      unitPrice = Number(giftType.split(',')[1])
    } catch (e) {
      console.error('回显加载礼品类型失败', e)
    }
    return unitPrice
  }

  // 判断当前编辑行是输入框还是选择框等
  getInput = (value) => {
    const inputType = this.props.column.inputType
    const dataIndex = this.props.column.dataIndex
    const formTypeData = this.props.column.value || []
    const attachmentImages = value || []
    if (inputType === 'select' && (dataIndex === 'type' || dataIndex === 'sendWayText' || dataIndex === 'address' || dataIndex === 'releaseType' || dataIndex === "gift" || dataIndex === "giftType")) {
      return <Select onChange={this.onChange}>
          {
            formTypeData.map((item) => {
              return (
                <Option value={`${item.messageKey},${item.remark},${item.code}`}>{item.messageKey}</Option>
              )
            })
          }
          </Select>
    } else if (inputType === 'chooser' && dataIndex === 'employeeName') {
      return  <Chooser
                single
                disabled={this.props.column.disabled}
                placeholder={messages('common.please.select')}
                labelKey="fullName"
                valueKey="employeeID"
                type="user"
            />
    } else if (inputType === 'chooser' && dataIndex === 'governmentName') {
      return  <Chooser
                placeholder={messages('common.please.select')}
                selectorItem={{
                  key: "code",
                  title: "选择",
                  columns: [
                    // {
                    //   title: "编码",
                    //   dataIndex: "code",
                    // },
                    { title: "名称", dataIndex: "messageKey" },
                  ],
                  searchForm: [],
                  url: `${config.baseUrl}/api/public/assembly/custom/enumerations/${formTypeData}`,
                }}
                single
                valueKey="code"
                labelKey="messageKey"
              />
    } else if (inputType === 'switch') {
      return <Switch defaultChecked={value} onChange={this.switchChange} className="switchWidth"/>
    } else if (inputType === 'upload') {
      return <FileUpload
                  showMaxNum={false}
                  fileSize={10}
                  defaultFileList={attachmentImages}
                  attachmentType="INVOICE_IMAGES"/>
    } else if (inputType === 'inputNumber' && (dataIndex === 'applyQuantity' || dataIndex === 'receiveQuantity' || dataIndex === 'quantity')) {
      return <InputNumber
                onChange={this.onInput}
                formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                parser={value => value.replace(/,/g, '')}
                min={0}/>
    } else if (inputType === 'inputNumber' && dataIndex === 'amount') {
      return <InputNumber
              formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
              parser={value => value.replace(/\$\s?|(,*)/g, '')}
              min={0}/>
    }
    return <Input/>;
  }

  render() {
    const { value } = this.state;
    const { editable, column, operationKey } = this.props
    const { getFieldDecorator } = this.props.form
    let newValue = column.dataIndex === 'isTwice' ? (value === '是' ? true : false) : value
    return (
      <div className="editable-cell">
        {editable && column.editable ? (
          <div className="editable-cell-input-wrapper">
            <div style={{paddingTop: column.dataIndex === 'appendix' ? '10px' : '0'}}>
              {
                column.isReadOnly && (
                  <Form.Item
                    style={{
                      margin: 0,
                    }}
                  >
                    {getFieldDecorator(column.dataIndex, {
                        initialValue: value,
                        rules: [
                            { required: column.isRequired, message: operationKey !== 'receiver' ? ' ' : `请输入${column.trueTitle ? column.trueTitle : column.title}!` },
                        ],
                    })(
                      column.inputType === 'inputNumber' ? <InputNumber
                        disabled
                        formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                        parser={value => value.replace(/\$\s?|(,*)/g, '')}
                      /> : <Input
                        disabled
                      />
                    )}
                  </Form.Item>
                )
              }
              {
                !column.isReadOnly && (
                  <Form.Item
                    style={{
                      margin: 0,
                    }}
                  >
                    {getFieldDecorator(column.dataIndex, {
                        initialValue: newValue,
                        rules: [
                            { required: column.isRequired, message: operationKey !== 'receiver' ? ' ' : `请输入${column.trueTitle ? column.trueTitle : column.title}!` },
                        ],
                    })(
                      this.getInput(newValue)
                    )}
                  </Form.Item>
                )
              }

            </div>
          </div>
        ) : (
          <div className="editable-cell-text-wrapper">
            {
              column.dataIndex === 'appendix' ?
                (value && value.length > 0 ? (<a onClick={() => this.showDraw(value)}>查看</a>) :'-') :
                (value ?
                  column.inputType === 'inputNumber' ?
                  column.dataIndex === 'amount' ? <Popover placement="topLeft" content={formatNumber(Number(value).toFixed(2))}>{formatNumber(Number(value).toFixed(2))}</Popover> : <Popover placement="topLeft" content={formatNumber(value)}>{formatNumber(value)}</Popover> :
                    <Popover placement="topLeft" content={value}>{value}</Popover>
                  : '-')
            }
          </div>
        )}
      </div>
    )
  }
}

class AddTableCell extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      columns:[],
      editingKey: '',
      visible: false,
      slideFrameKey: 'slideFrameKey0',
      fileList: [],
      value:[]
    }
  }

  componentWillReceiveProps (nextProps) {
    let { isEdit, isEditCancel, operationKey, columns, isCancleDeleteBtn, isCLBtn,onGiftChange, value } = nextProps
    if(value != this.state.value){
      this.setState({value})
    }
    columns.map(item => {
      item.render = (value, record) => {
        const editable = this.isEditing(record)
        return(<EditableCell value={value}
                    column={item}
                    editable={editable}
                    form={this.props.form}
                    clickFun={this.showDraw}
                    record={record}
                    onGiftChange={onGiftChange}
                    user={this.props.loginUser}
                    operationKey={operationKey}
                    isRequiredFun={this.changeIsRequired}/>
      )}
      if (item.needFixed) {
        item.fixed = 'left';
      }
    });
    if (isEdit) {
      columns.push(
        {
          title: messages('setting.key1097'/*操作*/),
          dataIndex: 'operation',
          width: 100,
          fixed: operationKey=== 'addTableA' ? false : 'right',
          key: operationKey,
          render: (text, record, index) => {
            const { editingKey } = this.state;
            const editable = this.isEditing(record);
            return editable ? (
              <span>
                <a
                  onClick={() => this.save(record, index)}
                  style={{ marginRight: 8 }}
                >
                  保存
                </a>
                <Popconfirm title="您真的要取消吗?" onConfirm={() => this.cancel(record.key)}>
                  <a>取消</a>
                </Popconfirm>
              </span>
            ) : (
              <span>
                {
                  !isEditCancel && (<a style={{ marginRight: 8 }} disabled={editingKey !== ''} onClick={() => this.edit(record.key, record)}>
                  编辑
                  </a>)
                }
                {
                  !isCancleDeleteBtn && (
                    <Popconfirm title="您真的要删除这条数据吗?" onConfirm={() => this.onDelete(record)}>
                        <a style={{ marginRight: 8 }} disabled={editingKey !== ''}>删除</a>
                    </Popconfirm>
                  )
                }
                {/* {
                  isCLBtn && (
                    <Popconfirm title="是否确认签收?" onConfirm={() => this.onConfirm(record)}>
                        <a style={{ marginRight: 8 }}>确认签收</a>
                    </Popconfirm>
                  )
                }
                {
                  isCLBtn && (
                    <Popconfirm title="是否确认遗失?" onConfirm={() => this.onLose(record)}>
                        <a style={{ marginRight: 8 }}>卡券遗失</a>
                    </Popconfirm>
                  )
                } */}
              </span>
            );
          },
        }
      )
    }
    else {
      if(isCLBtn){
        columns.push(
          {
            title: messages('setting.key1097'/*操作*/),
            dataIndex: 'operation',
            width: 100,
            fixed: 'right',
            key: operationKey,
            render: (text, record, index) => {
              return (
                <span>
                  {
                    isCLBtn && (
                      <Popconfirm title="是否确认签收?" onConfirm={() => this.onConfirm(record)}>
                          <a disabled={!(record.distributionStatus === '已发货' && record.signingStatus === "待签收")} style={{ marginRight: 8 }}>确认签收</a>
                      </Popconfirm>
                    )
                  }
                  {
                    isCLBtn && (
                      <Popconfirm title="是否确认遗失?" onConfirm={() => this.onLose(record)}>
                          <a disabled={!(record.distributionStatus === '已发货' && record.signingStatus === "待签收")} style={{ marginRight: 8 }}>卡券遗失</a>
                      </Popconfirm>
                    )
                  }
                </span>
              );
            },
          }
        )
      }

    }
    this.setState({
      columns: uniqueObjArr(columns, 'dataIndex')
    })
  }

  componentDidMount() {
    this.props.onRef(this)
    this.setState({value: this.props.value})
  }

  onConfirm = (i) => {
   this.props.onConfirm(i);
  }

  onLose = (i) => {
    this.props.onLose(i);
  }

  showDraw = (value) => {
    this.setState({
      fileList: value,
      visible: true
    })
  }

  changeIsRequired = (value, dataIndex) => {
    let {columns} = this.state
    let index = columns.findIndex(item => item.dataIndex === dataIndex)
    columns[index].editable = value
    this.setState({
      columns
    })
  }

  renderContent = () => {
    let { fileList } = this.state
    return (
      <div>
        {
          fileList.map(item => {
            return <a href={item.fileURL} target="_blank">{item.fileName}</a>
          })
        }
        <div className="slide-footer">
          <Button onClick={this.handleOnHideSlide}>确定</Button>
        </div>
      </div>
      )
  }

  /**
   * 关闭抽屉
   */
  handleOnHideSlide = () => {
    this.setState({
      visible: false
    })
  }

  /**
   *  判断当前是否需要有输入框编辑
  */
  isEditing = record => record.key === this.state.editingKey;

  /**
   * 取消
  */
  cancel = () => {
    this.props.onChangeEdit(false);
    this.setState({ editingKey: '' });
  };

 /**
   * 保存
   * record 当前保存按钮的表格的行数据
   * index 当前保存按钮的表格的行数
   * row 当前保存行的编辑的数据
  */
  save(record, index) {
    this.props.form.validateFields((error, row) => {
      //其他单子是后端校验的，但是工会没有后端校验
      if (error && (this.props.operationKey !== 'receiver'|| this.props.formCode==='SQ004')) {
        message.info('请将输入框填写完整再保存！')
        return;
      }
      this.onChange('onSave', {
        record,
        index,
        row: {
          ...row,
          employeeName: row.employeeName || [{
            fullName: this.props.info && this.props.info.applicant && this.props.info.applicant.fullName,
            employeeID: this.props.info && this.props.info.applicant && (this.props.info.applicant.employeeID || this.props.info.applicant.employeeId)
          }]
        },
        unitPrice: Number((this.props.form.getFieldValue('giftType')||'').split(',')[1]) || record.unitPrice
      })

      // this.props.onChangeEdit(false);
    });
  }

  /**
   * 编辑
  */
  edit (key, record) {
    if(this.props.editLines){
      message.warning('已经有一行在编辑中未保存')
      return;
    }
    this.props.onChangeEdit(true);
    let {columns} = this.state
    let index = columns.findIndex(item => item.dataIndex === 'deliveryInfo')
    let indexType = columns.findIndex(item => item.dataIndex === 'type')
    if(record.gift && this.props.operationKey == 'receiver'){
      let formType='';
      const gift= record.gift;
      if(gift==='礼品卡') {
        formType = 2
      } else if(gift==='BOG'){
        formType = 3
      } else if(gift==='现金券'){
        formType = 7
      }
      this.props.onGiftChange(formType)
    }
    if (indexType && columns[indexType] && !columns[indexType].editable && index && columns[index]) {
      if (record.sendWayText === '自取') {
        columns[index].editable = false
      } else {
        columns[index].editable = true
      }
    }
    let isTwiceIndex = columns.findIndex(item => item.dataIndex === 'isTwice')
    let isTwiceIndexType = columns.findIndex(item => item.dataIndex === 'remark')
    if (isTwiceIndexType && columns[isTwiceIndexType] && isTwiceIndex && columns[isTwiceIndex]) {
      if (record.isTwice === '是') {
        columns[isTwiceIndexType].editable = true
      } else {
        columns[isTwiceIndexType].editable = false
      }
    }
    this.setState({
        editingKey: key,
        columns
    }, () => {
      if (record.employeeName) {
        this.props.form.setFieldsValue({
          employeeName: [{fullName: record.employeeName, employeeID: record.employeeId}]
        })
      }else{
        if(this.props.fafangleixing === '002'){
          this.props.form.setFieldsValue({
            employeeName: [{fullName: this.props.info.applicant.fullName, employeeID: this.props.info.applicant.employeeId}]
          })
        }
      }
      if (record.governmentName) {
        this.props.form.setFieldsValue({
          governmentName: [{messageKey: record.governmentName, code: record.governmentCode}]
        })
      }
    })
  }

  /**
   * 删除
  */
  onDelete = (record) => {
    if(this.props.editLines){
      message.warning('已经有一行在编辑中未保存')
      return;
    }
    this.onChange('onDelete', record)
  };

  /**
   * 增加
  */
  handleAdd = (obj) => {
    if(this.props.editLines){
      message.warning('已经有一行在编辑中未保存')
      return;
    }
    this.props.onChangeEdit(true);
    const { editingKey } = this.state
    const { value } = this.props
    if (editingKey) {
      return
    }
    let key = new Date().getTime();
    let newData = {key: key};
    this.props.columns.map(item => {
      if (item.defaultValue) {
        newData[item.dataIndex] = item.defaultValue
      }
    });
    value.push(newData);
    this.onChange('onChange', value)
    this.setState({
      editingKey: key
    }, () => {
      if (obj) {
        this.props.form.setFieldsValue({
          employeeName: [{fullName: obj.fullName, employeeID: obj.employeeID}],
          address: obj.address ? obj.address : undefined,
          contactWay: obj.contactWay ? obj.contactWay : undefined
        })
      }
    })
  };

  /**
   * 编辑、保存触发父组件的统一方法
  */
  onChange = (Func, changedValue) => {
    if (this.props[Func]) {
      this.props[Func](changedValue)
    }
  };

  //选中项发生变化的时的回调
  onSelectChange = (selectedRowKeys) => {
    this.setState({ selectedRowKeys })
  };

  //选择/取消选择某行的回调
  handleSelectRow = (record, selected) => {
    let selectedOID = this.state.selectedOID;
    if (selected) {
      selectedOID.push(record.formOid)
    } else {
      selectedOID.delete(record.formOid)
    }
    this.setState({ selectedOID })
  };

  //选择/取消选择所有行的回调
  handleSelectAllRow = (selected, selectedRows, changeRows) => {
    let selectedOID = this.state.selectedOID;
    if(selected) {
      changeRows.map(item => {
        selectedOID.push(item.formOid)
      })
    } else {
      changeRows.map(item => {
        selectedOID.delete(item.formOid)
      })
    }
    this.setState({ selectedOID })
  };


  render() {
    const { columns, slideFrameKey, visible, selectedRowKeys,value } = this.state;
    const { loading, title, rowSelection } = this.props;
    // const rowSelection = {
    //   selectedRowKeys: selectedRowKeys,
    //   onChange: this.onSelectChange,
    //   onSelect: this.handleSelectRow,
    //   onSelectAll: this.handleSelectAllRow
    // };
    return (
      <div>
        <Form>
          <ResizeTable rowKey="key"
                loading={loading}
                dataSource={value}
                columns={columns}
                pagination={false}
                scroll={{x:true}}
                title={title}
                rowSelection={rowSelection}
                bordered
                size="middle"
                />
        </Form>

        <SlideFrame
          slideFrameKey={slideFrameKey}
          title={messages('request.key805')}
          width={'730px'}
          show={visible}
          content={this.renderContent}
          onClose={this.handleOnHideSlide}
        />
      </div>
    );
  }
}

/**
 *
 * @type columns，每项格式和table的columns一样，新增以下字段
 * {
      editable: false,         //可选，是否可编辑
      isRequired: false,      //可选，是否必填
      defaultValue: '',      //可选，默认值
      inputType： '', // 输入框的类型 input select
 * }
 */
AddTableCell.propTypes = {
  columns: React.PropTypes.array.isRequired,
  value: React.PropTypes.array, // 当前table的列表数据
  onChange: React.PropTypes.func,  //修改当前table列表数据
  onDelete: React.PropTypes.func,  //删除的回调
  onSave: React.PropTypes.func,  //保存后的回调
};

AddTableCell.defaultProps={
  value: [],
};

function mapStateToProps(state) {
  return {
    loginUser: state.login.loginUser
  }
}

const WrappedAddTableCell = Form.create()(AddTableCell);

export default connect(mapStateToProps)(WrappedAddTableCell)
